package marchenko.springdao.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import marchenko.springdao.domain.Author;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class AuthorRepositoryImpl implements AuthorRepository {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public Author find(Integer id) throws DataAccessException {
		return jdbcTemplate.queryForObject(
				"select * from authors where id = ?", new AuthorMapper(), id);
	}

	public Author findByName(String name) throws DataAccessException {
		return jdbcTemplate.queryForObject(
				"select * from authors where name = ?", new AuthorMapper(),
				name);
	}

	public List<Author> findAll() throws DataAccessException {
		return jdbcTemplate.query("select * from authors", new AuthorMapper());
	}

	public boolean create(Author newinstance) throws DataAccessException {
		return jdbcTemplate.update("insert into authors values (?,?)",
				newinstance.getAuthorId(),
				newinstance.getAuthorName()) > 0;
	}

	public boolean deleteById(Integer id) throws DataAccessException {
		return jdbcTemplate.update("delete from authors where id = ?", id) > 0;
	}

	private static final class AuthorMapper implements RowMapper<Author> {

		public Author mapRow(ResultSet resultSet, int i) throws SQLException {
			Author author = new Author();
			author.setAuthorId(resultSet.getInt("id"));
			author.setAuthorName(resultSet.getString("name"));
			return author;
		}
	}

}
